﻿namespace Rio.Framework.Pages.Controls.BaseClass
{
    #region Using
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.IO;
    using System.Linq;
    using System.ServiceModel.DomainServices.Client;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Media;
    using System.Windows.Threading;
    using System.Xml.Linq;
    using NetBay.Core.BusinessEntities;
    using Rio.Applications.Web.Services;
    using Rio.Framework.Localisation;
    using Rio.Framework.Pages.CriteriaControls;
    using Rio.Framework.Pages.Manager;
    using Rio.Framework.Pages.ModalControls;
    using Rio.Framework.Pages.UserControls;
    using Rio.Framework.Pages.Viewer;
    using Rio.Framework.WCFService;
    using ImageRio = Rio.Framework.WCFService.RioWcfServices.ImageRio;
    using RIOWCFSERVICE = Rio.Framework.WCFService.RioWcfServices;
    using Rio.Framework.Pages.AppCode.Enums;
    using Rio.Framework.Pages.Context;
    #endregion


    /// <summary>
    /// This class represent base class of all index panel
    /// </summary>
    public class IndexPanelBase : ControlBase
    {
        #region Attributs

        private AppDisplayMode _currentIndexMode = AppDisplayMode.None;
        private FolderType _currentFolderType;
        private Organization _organization;
        private Organization _currentOrganization;
        private FolderType _folderType;
        private Folder _currentFolder;

        #region Label for translation
        protected string m_szLabelMandatoryField;
        protected string m_szLabelIndexedDocument;
        protected string m_szLabelIndexedDocumentFailed;
        protected string m_szMsgNoDocumentSelected;
        protected string m_szMsgNoOcrMaskFound;
        protected string m_szLabelNoImageSelected = string.Empty;
        protected string m_szMsgFolderExists = string.Empty;
        protected string m_szMsgNoUnicity = string.Empty;
        #endregion

        protected SplashScreen m_oSplashscreen;
        protected string m_sLblNoCriteria;
        protected List<Index> m_oListIndex;
        protected long ChronoId = 0;
        protected string ChronoName = string.Empty;
        protected int m_iCounterIndexedDocOk;
        protected int m_iCounterErrorOnIndex;
        protected ThumbnailPanel m_oListVignetteFromImportPage;
        protected UCViewer m_oViewerControlFromImportPage;
        protected ListViewer m_oListViewer;
        protected int m_iNumberOfDocAdd = 0;
        protected int m_iNumberOfAddedDoc = 0;
        protected int m_iNumberOfDocumentToAdd = 0;
        protected int m_iActivePanel = 0;

        #endregion

        #region Properties

        /// <summary>
        /// Getor Set the a List of Thumbnails selected
        /// </summary>
        /// <value>The m_o list selected filename.</value>
        public List<Rio.Framework.WCFService.RioWcfServices.ImageRio> m_oListSelectedFilename { get; set; }

        /// <summary>
        /// Get or set a list of imported directories
        /// </summary>
        /// <value>The m_ directory list to import.</value>
        protected List<Rio.Framework.WCFService.RioWcfServices.ImageRio> m_DirectoryListToImport { get; set; }
        
        /// <summary>
        /// Gets or sets the current index mode.
        /// </summary>
        /// <value>The current index mode.</value>
        protected AppDisplayMode CurrentIndexMode
        {
            get { return _currentIndexMode; }
            set
            {
                _currentIndexMode = value;
                OnPropertyChanged("CurrentIndexMode");
            }
        }

        /// <summary>
        /// Organzation selected
        /// </summary>
        /// <value>The organization.</value>
        public Organization m_oOrganization
        {
            get { return _organization; }
            set
            {
                _organization = value;
                OnPropertyChanged("m_oOrganization");
            }
        }

        /// <summary>
        /// Gets or sets the m_o current organization.
        /// </summary>
        /// <value>The current organization.</value>
        public Organization m_oCurrentOrganization
        {
            get { return _currentOrganization; }
            set
            {
                _currentOrganization = value;
                OnPropertyChanged("m_oCurrentOrganization");
            }
        }

        /// <summary>
        /// FolderType selected
        /// </summary>
        public FolderType m_oFolderType
        {
            get { return _folderType; }
            set
            {
                _folderType = value;
                OnPropertyChanged("m_oFolderType");
            }
        }

        /// <summary>
        /// Gets or sets the type of the m_o current folder.
        /// </summary>
        /// <value>The type of the m_o current folder.</value>
        public FolderType m_oCurrentFolderType
        {
            get { return _currentFolderType; }
            set
            {
                _currentFolderType = value;
                OnPropertyChanged("m_oCurrentFolderType");
            }
        }

        /// <summary>
        /// Current folder
        /// </summary>
        /// <value>The current folder.</value>
        public Folder CurrentFolder
        {
            get { return _currentFolder; }
            set
            {
                _currentFolder = value;
                OnPropertyChanged("CurrentFolder");
            }
        }

        #endregion

        #region Events

        public event EventHandler BeforeIndexing;
        public void OnBeforeIndexing()
        {
            if (this.BeforeIndexing != null)
            {
                BeforeIndexing(this, new EventArgs());
            }
        }

        public event EventHandler GoToThumbnailMode;
        public void OnGoToThumbnailMode()
        {
            if (this.GoToThumbnailMode != null)
            {
                GoToThumbnailMode(this, new EventArgs());
            }
        }

        public event SearchFinishedHandler SearchFinished;
        public delegate void SearchFinishedHandler(object sender, ObservableCollection<Folder> e);
        protected void OnSearchFinished(ObservableCollection<Folder> e)
        {
            if (this.SearchFinished != null)
            {
                this.SearchFinished(this, e);
            }
        }

        //Event raised when the documents has been indexed
        public event EventHandler Indexed;
        public delegate void IndexEventHandler(object sender, EventArgs e);
        protected void OnIndexed()
        {
            if (Indexed != null)
                Indexed(this, EventArgs.Empty);
        }

        /// <summary>
        /// Event fired when all indexes are loaded in StackPanel.
        /// This is useful when an import bu uri.
        /// </summary>
        public event IndexEventHandler IndexLoaded;
        public void OnIndexLoaded()
        {
            if (this.IndexLoaded != null)
            {
                IndexLoaded(this, new EventArgs());
            }
        }

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="IndexPanelBase" /> class.
        /// </summary>
        public IndexPanelBase()
        {
            if (!IsInDesignMode)
            {
                m_oSplashscreen = new SplashScreen();
            }
        }

        #endregion

        #region Virtual Functions

        /// <summary>
        /// Used to set Label localization
        /// </summary>
        public override void InitLabel()
        {
            m_sLblNoCriteria = Resx.GetLabel(ResxSearchPanel.MSG_NO_CRITERIA);
            m_szLabelMandatoryField = Resx.GetLabel(ResxIndexPanel.MANDATORYFIELD);
            m_szLabelNoImageSelected = Resx.GetLabel(ResxIndexPanel.MSG_NO_IMAGE_SELECTED);
            m_szLabelIndexedDocument = Resx.GetLabel(ResxIndexPanel.INDEXEDDOCUMENT);
            m_szLabelIndexedDocumentFailed = Resx.GetLabel(ResxIndexPanel.INDEXEDDOCUMENTFAILED);
            m_szMsgFolderExists = Resx.GetLabel(ResxIndexPanel.MSG_FOLDER_EXISTS);
            m_szMsgNoUnicity = Resx.GetLabel(ResxIndexPanel.MSG_NO_UNICITY);
            m_szMsgNoDocumentSelected = Resx.GetLabel(ResxIndexPanel.MSG_NO_DOCUMENT_SELECTED);
            m_szMsgNoOcrMaskFound = Resx.GetLabel(ResxIndexPanel.MSG_NO_OCRMASK_FOUND);
        }

        /// <summary>
        /// Index selected files in viewer
        /// </summary>
        public virtual void IndexFiles()
        { }

        /// <summary>
        /// Searches the specified organization.
        /// </summary>
        /// <param name="organization">The organization.</param>
        /// <param name="folderType">Type of the folder.</param>
        /// <param name="indexWithValues">The index with values.</param>
        protected virtual void Search(Organization organization, FolderType folderType, Dictionary<long, string> indexWithValues)
        {
            /*
             * Validation
             */

            if (organization == null)
            {
                throw new Exception("Organization is null");
            }

            if (folderType == null)
            {
                throw new Exception("FolderType is null");
            }

            if (indexWithValues == null || String.IsNullOrWhiteSpace(String.Concat(indexWithValues.Values)))
            {
                throw new Exception("There is no criterias");
            }

            /*
             * Splashscreen
             */

            m_oSplashscreen.Message = Resx.GetLabel(ResxCommon.SPLASHSCREEN_MESSAGE);
            m_oSplashscreen.Show();
            ModalDialogController.Launch(m_oSplashscreen);

            /*
             * Request
             */
            var query = GetDataContext.GetFoldersQuery(organization.Identifier,
                                                folderType.Identifier,
                                                indexWithValues);

            GetDataContext.Load(query, OnGetFoldersQueryCallback, null);
        }

        #endregion

        #region Public Functions

        /// <summary>
        /// Activate the Panel
        /// </summary>
        public void ActivatePanel()
        {
            IsEnabled = true;
        }

        /// <summary>
        /// Desactive the Panel
        /// </summary>
        public void DesactivatePanel()
        {
            IsEnabled = false;
        }

        #endregion

        #region Protected Functions

        /// <summary>
        /// Called when [get folders query callback].
        /// </summary>
        /// <param name="result">The result.</param>
        private void OnGetFoldersQueryCallback(LoadOperation<Folder> result)
        {
            OnSearchFinished(new ObservableCollection<Folder>(result.Entities));

            ModalDialogController.Close();
            m_oSplashscreen.Close();
        }

        /// <summary>
        /// Used to delete an import directory then refresh viewer
        /// </summary>
        /// <param name="DirectoryList">The directory list.</param>
        protected void DeleteDirectoriesWcfCall(List<ImageRio> DirectoryList)
        {
            WCFService.RioWcfServices.WCFServiceClient L_oWCFServiceClient = ServiceManager.GetRioWCFServiceClient();
            L_oWCFServiceClient.DeleteImportDirectoriesCompleted += ((obj, args) =>
            {
                RefreshViewer();
            });
            ObservableCollection<string> dir = new ObservableCollection<string>();
            foreach (ImageRio img in DirectoryList)
            {
                dir.Add(img.Name);
            }
            L_oWCFServiceClient.DeleteImportDirectoriesAsync(dir, GlobalWebContext.CurrentUser.UserId, ServiceManager.GetLicenseKey());
        }

        /// <summary>
        /// Used to delete an import directory then refresh viewer
        /// </summary>
        /// <param name="DirectoryName">Name of the directory.</param>
        protected void DeleteDirectoryWcfCall(string DirectoryName)
        {
            WCFService.RioWcfServices.WCFServiceClient L_oWCFServiceClient = ServiceManager.GetRioWCFServiceClient();
            L_oWCFServiceClient.DeleteImportDirectoriesCompleted += ((obj, args) =>
            {
                RefreshViewer();
            });
            ObservableCollection<string> dir = new ObservableCollection<string>() { DirectoryName };
            L_oWCFServiceClient.DeleteImportDirectoriesAsync(dir, GlobalWebContext.CurrentUser.UserId, ServiceManager.GetLicenseKey());
        }

        /// <summary>
        /// Used to refresh all viewer
        /// </summary>
        protected void RefreshViewer()
        {
            m_oListVignetteFromImportPage.LoadVignettes(-1, true);
            m_oListViewer.RefreshItems(true);
            m_oViewerControlFromImportPage.RefreshItems(true);
        }

        #endregion

    }
}
